/**
 * Copyright (C), 2001-2023, www.bosssof.com.cn
 * FileName: RedisConfig
 * Author: chen
 * Date: 2024-05-29 09:28:47
 * Description:
 * 配置 Redis 的相关设置，包括序列化器和 RedisTemplate 的配置。
 * <p>
 * History:
 * <author> chen
 * <time> 2024-05-29 09:28:47
 * <version> 1.0.0
 * <desc> 版本描述
 */
package com.bosssoft.g1.common.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @ClassName: RedisConfig
 * @Description: 配置 RedisTemplate 的配置类，主要设置 key 和 value 的序列化方式。
 * @Author: chen
 * @Date: 2024-05-29 09:28:47
 **/
@Configuration
public class RedisConfig {

    /**
     * 创建 RedisTemplate 的 Bean 配置。
     *
     * @param redisConnectionFactory Redis 连接工厂。
     * @return 配置好的 RedisTemplate 实例。
     */
    @Bean
    public RedisTemplate<String, Object> createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // JSON 序列化配置
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // String 的序列化配置
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();

        return template;
    }
}
